/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.spreadsheet.analyze.preview;

import cn.ac.nercis.pes.common.utils.JsonUtils;
import cn.ac.nercis.pes.community.component.spreadsheet.TableSheetView;
import cn.ac.nercis.pes.community.model.vo.evaluation.UnitEvaluationVO;
import cn.ac.nercis.pes.community.support.event.EventCallback;
import cn.ac.nercis.pes.community.utils.IconUtils;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 单元指标测评预览表控件
 *
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class UnitEvalPreviewSheetView extends TableSheetView<UnitEvaluationVO> {
    private final static Integer EMPTY_DATA_COUNT = 1;
    private final static List<String> COLUMNS = List.of("测评指标", "符合情况", "结果分析");
    private final static Integer NAME_COLUMN_INDEX = 0;
    private final static Integer CONCLUSION_COLUMN_INDEX = 1;
    private final static Integer ANALYSIS_COLUMN_INDEX = 2;

    private EventCallback<UnitEvaluationVO> onOptionAction;

    public UnitEvalPreviewSheetView() {
        this.getStyleClass().add("pes-sheet-view");

        var grid = new GridBase(EMPTY_DATA_COUNT, COLUMNS.size());
        grid.getColumnHeaders().addAll(COLUMNS);
        grid.setRowHeightCallback(new GridBase.MapBasedRowHeightFactory(heardRowHeight()));
        setGrid(grid);
        getColumns().get(NAME_COLUMN_INDEX).setPrefWidth(200);
        getColumns().get(CONCLUSION_COLUMN_INDEX).setPrefWidth(200);
        getColumns().get(ANALYSIS_COLUMN_INDEX).setPrefWidth(500);
    }

    public void initialize(EventCallback<UnitEvaluationVO> onOptionAction) {
        this.onOptionAction = onOptionAction;
        this.editModel.set(false);
    }

    public void loadContent(List<UnitEvaluationVO> data) {
        this.editModel.set(false);
        this.sheetData = data;
        this.clearContent();
        for (var dataIndex = 0; dataIndex < data.size(); dataIndex++) {
            this.loadContent(data.get(dataIndex), toSheetRowIndex(dataIndex));
        }
        setGrid(getGrid());
        this.editModel.set(true);
    }

    public List<UnitEvaluationVO> getModifyData() {
        List<UnitEvaluationVO> data = new ArrayList<>();
        for (var sheetRowIndex = 0; sheetRowIndex < this.getGrid().getRows().size(); sheetRowIndex++) {
            if (this.isEmptyData(sheetRowIndex)) {
                continue;
            }
            data.add(getModifyData(sheetRowIndex));
        }
        return data.stream()
                .filter(item -> Objects.nonNull(item) && item.isChange())
                .collect(Collectors.toList());
    }

    @Override
    public ContextMenu getSpreadsheetViewContextMenu() {
        return generateContextMenu(false);
    }


    private UnitEvaluationVO getModifyData(Integer sheetRowIndex) {
        if (toDataIndex(sheetRowIndex) < 0) {
            return null;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        UnitEvaluationVO info;
        if (toDataIndex(sheetRowIndex) < this.sheetData.size()) {
            info = this.sheetData.get(toDataIndex(sheetRowIndex));
        } else {
            return null;
        }
        info.setResultAnalysis(rowData.get(ANALYSIS_COLUMN_INDEX).getText());
        return info;
    }

    protected Map<Integer, Double> heardRowHeight() {
        Map<Integer, Double> rowHeight = new HashMap<>(1);
        IntStream.range(0, 20).forEach(number -> rowHeight.put(number, 100.0));
        return rowHeight;
    }

    @Override
    protected void loadContent(UnitEvaluationVO info, Integer sheetRowIndex) {
        final ObservableList<SpreadsheetCell> data = FXCollections.observableArrayList();
        AtomicInteger columnIndex = new AtomicInteger(0);
        data.add(getTextAreaCell(sheetRowIndex, columnIndex.getAndIncrement(), info.getUnitTargetName(), false));
        data.add(getTextFieldCell(sheetRowIndex, columnIndex.getAndIncrement(), info.getConclusion().getName(), false));
        data.add(getTextAreaCell(sheetRowIndex, columnIndex.getAndIncrement(), info.getResultAnalysis(), true, "data-cell-left"));
        var optionCell = getOptionCell(sheetRowIndex, columnIndex.getAndIncrement());
        Button option = new Button();
        option.getStyleClass().add("sheet-view-option-button");
        option.setGraphic(IconUtils.getGlyph("evaluation-button-icon", "sheet-view-option-icon"));
        String unitTargetId = info.getUnitTargetId();
        option.setOnAction((event) -> {
            var currentInfo = this.sheetData.stream()
                    .filter(s -> StringUtils.equals(s.getUnitTargetId(), unitTargetId))
                    .findFirst().orElse(null);
            if (Objects.nonNull(this.onOptionAction) && Objects.nonNull(currentInfo)) {
                log.info(JsonUtils.toJson(currentInfo));
                this.onOptionAction.action(currentInfo);
            }
        });
        optionCell.setGraphic(option);
        data.add(optionCell);
        this.getGrid().getRows().add(data);
        info.resetChange();
    }

    @Override
    protected void clearContent(){
        int endIndex = this.getGrid().getRows().size() -1;
        for(;endIndex>=0;endIndex--){
            this.getGrid().getRows().remove(endIndex);
        }
    }

    @Override
    protected boolean isEmptyData(Integer sheetRowIndex) {
        return toDataIndex(sheetRowIndex) < 0;
    }

    @Override
    protected boolean validate(ObservableList<SpreadsheetCell> rowData) {
        return true;
    }

    @Override
    protected void clearValidate(ObservableList<SpreadsheetCell> rowData) {
    }

    @Override
    protected List<String> getDataColumns() {
        return COLUMNS;
    }

    @Override
    protected ObservableList<SpreadsheetCell> generateEmptyDataRow(int rowIndex) {
        return null;
    }

    @Override
    protected void deleteData() {
    }
}